package main

import (
	"context"
	"log"
	"ourplansystem/server/database"
	"ourplansystem/server/handlers"
	"ourplansystem/server/middleware"
	"ourplansystem/server/models"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
)

func main() {
	// 数据库配置
	dbConfig := database.Config{
		Host:     "47.121.177.183",
		Port:     "5432",
		User:     "postgres",
		Password: "123",
		DBName:   "ourPlanSystem",
	}

	// 创建数据库客户端
	client, err := database.NewClient(dbConfig)
	if err != nil {
		log.Fatalf("数据库连接失败: %v", err)
	}
	defer client.Close()

	log.Println("数据库连接成功")

	// 自动迁移数据库表
	ctx := context.Background()
	if err := database.AutoMigrate(ctx, client); err != nil {
		log.Fatalf("数据库迁移失败: %v", err)
	}

	// 初始化种子数据
	if err := database.SeedData(ctx, client); err != nil {
		log.Fatalf("初始数据创建失败: %v", err)
	}

	// 创建所有处理器
	authHandler := handlers.NewAuthHandler(client)
	userHandler := handlers.NewUserHandler(client)
	scheduleHandler := handlers.NewScheduleHandler(client)
	countdownHandler := handlers.NewCountdownHandler(client)
	bottleHandler := handlers.NewBottleHandler(client)
	anniversaryHandler := handlers.NewAnniversaryHandler(client)
	dailyCheckinHandler := handlers.NewDailyCheckinHandler(client)
	noteHandler := handlers.NewNoteHandler(client)
	photoHandler := handlers.NewPhotoHandler(client)
	wishHandler := handlers.NewWishHandler(client)
	goalHandler := handlers.NewGoalHandler(client)
	qaRecordHandler := handlers.NewQARecordHandler(client)
	mediaRecordHandler := handlers.NewMediaRecordHandler(client)
	giftHandler := handlers.NewGiftHandler(client)
	relationshipStatHandler := handlers.NewRelationshipStatHandler(client)

	// 创建 Fiber 实例
	app := fiber.New(fiber.Config{
		ErrorHandler: models.ErrorHandler,
		BodyLimit:    50 * 1024 * 1024, // 允许最大 50MB 的请求体
	})

	// 中间件
	app.Use(logger.New())
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowHeaders: "*",
		AllowMethods: "*",
	}))

	// 静态文件服务（用于访问上传的图片）
	app.Static("/uploads", "./uploads")

	// 路由
	api := app.Group("/api")

	// Health Check 路由
	api.Get("/health", func(c *fiber.Ctx) error {
		return models.Success(c, fiber.Map{
			"status":  "ok",
			"service": "OurPlanSystem API",
			"message": "热重载测试成功!",
		})
	})

	// Auth 路由 - 认证
	auth := api.Group("/auth")
	auth.Post("/login", authHandler.Login)

	// User 路由 - 用户管理（需要JWT认证）
	users := api.Group("/users", middleware.JWTAuth())
	users.Get("/", userHandler.GetUsers)
	users.Get("/:id", userHandler.GetUser)
	users.Post("/", userHandler.CreateUser)
	users.Put("/:id", userHandler.UpdateUser)
	users.Delete("/:id", userHandler.DeleteUser)

	// Schedule 路由 - 日程管理（需要JWT认证）
	schedules := api.Group("/schedules", middleware.JWTAuth())
	schedules.Get("/", scheduleHandler.GetSchedules)
	schedules.Get("/deleted", scheduleHandler.GetDeletedSchedules) // 获取已删除的日程
	schedules.Get("/:id", scheduleHandler.GetSchedule)
	schedules.Post("/", scheduleHandler.CreateSchedule)
	schedules.Put("/:id", scheduleHandler.UpdateSchedule)
	schedules.Put("/:id/restore", scheduleHandler.RestoreSchedule)              // 恢复日程
	schedules.Delete("/:id", scheduleHandler.DeleteSchedule)                    // 软删除
	schedules.Delete("/:id/permanent", scheduleHandler.PermanentDeleteSchedule) // 永久删除

	// Countdown 路由 - 倒计时（需要JWT认证）
	countdowns := api.Group("/countdowns", middleware.JWTAuth())
	countdowns.Get("/", countdownHandler.GetCountdowns)
	countdowns.Get("/:id", countdownHandler.GetCountdown)
	countdowns.Post("/", countdownHandler.CreateCountdown)
	countdowns.Put("/:id", countdownHandler.UpdateCountdown)
	countdowns.Delete("/:id", countdownHandler.DeleteCountdown)

	// Bottle 路由 - 漂流瓶（需要JWT认证）
	bottles := api.Group("/bottles", middleware.JWTAuth())
	bottles.Get("/", bottleHandler.GetBottles)
	bottles.Get("/deleted", bottleHandler.GetDeletedBottles) // 获取已删除的漂流瓶
	bottles.Get("/random", bottleHandler.GetRandomBottle)    // 随机获取一个漂流瓶
	bottles.Get("/:id", bottleHandler.GetBottle)
	bottles.Post("/", bottleHandler.CreateBottle)
	bottles.Put("/:id", bottleHandler.UpdateBottle)
	bottles.Put("/:id/restore", bottleHandler.RestoreBottle)              // 恢复漂流瓶
	bottles.Delete("/:id", bottleHandler.DeleteBottle)                    // 软删除
	bottles.Delete("/:id/permanent", bottleHandler.PermanentDeleteBottle) // 永久删除

	// Anniversary 路由 - 纪念日（需要JWT认证）
	anniversaries := api.Group("/anniversaries", middleware.JWTAuth())
	anniversaries.Get("/", anniversaryHandler.GetAnniversaries)
	anniversaries.Get("/:id", anniversaryHandler.GetAnniversary)
	anniversaries.Post("/", anniversaryHandler.CreateAnniversary)
	anniversaries.Put("/:id", anniversaryHandler.UpdateAnniversary)
	anniversaries.Delete("/:id", anniversaryHandler.DeleteAnniversary)

	// DailyCheckin 路由 - 每日打卡（需要JWT认证）
	checkins := api.Group("/checkins", middleware.JWTAuth())
	checkins.Get("/", dailyCheckinHandler.GetDailyCheckins)
	checkins.Get("/:id", dailyCheckinHandler.GetDailyCheckin)
	checkins.Get("/user/:userId", dailyCheckinHandler.GetUserCheckins) // 获取指定用户的打卡记录
	checkins.Post("/", dailyCheckinHandler.CreateDailyCheckin)
	checkins.Delete("/:id", dailyCheckinHandler.DeleteDailyCheckin)

	// Note 路由 - 情侣小纸条（需要JWT认证）
	notes := api.Group("/notes", middleware.JWTAuth())
	notes.Get("/", noteHandler.GetNotes)
	notes.Get("/deleted", noteHandler.GetDeletedNotes) // 获取已删除的小纸条
	notes.Get("/:id", noteHandler.GetNote)
	notes.Get("/received/:userId", noteHandler.GetReceivedNotes) // 获取收到的小纸条
	notes.Get("/sent/:userId", noteHandler.GetSentNotes)         // 获取发送的小纸条
	notes.Post("/", noteHandler.CreateNote)
	notes.Put("/:id", noteHandler.UpdateNote)
	notes.Put("/:id/restore", noteHandler.RestoreNote)              // 恢复小纸条
	notes.Delete("/:id", noteHandler.DeleteNote)                    // 软删除
	notes.Delete("/:id/permanent", noteHandler.PermanentDeleteNote) // 永久删除

	// Photo 路由 - 照片墙（需要JWT认证）
	photos := api.Group("/photos", middleware.JWTAuth())
	photos.Get("/", photoHandler.GetPhotos)
	photos.Get("/deleted", photoHandler.GetDeletedPhotos) // 获取已删除的照片
	photos.Get("/:id", photoHandler.GetPhoto)
	photos.Post("/", photoHandler.CreatePhoto)
	photos.Post("/upload", photoHandler.UploadPhoto)                   // 上传照片文件
	photos.Put("/:id", photoHandler.UpdatePhoto)
	photos.Put("/:id/restore", photoHandler.RestorePhoto)              // 恢复照片
	photos.Delete("/:id", photoHandler.DeletePhoto)                    // 软删除
	photos.Delete("/:id/permanent", photoHandler.PermanentDeletePhoto) // 永久删除

	// Wish 路由 - 愿望清单（需要JWT认证）
	wishes := api.Group("/wishes", middleware.JWTAuth())
	wishes.Get("/", wishHandler.GetWishes)
	wishes.Get("/:id", wishHandler.GetWish)
	wishes.Post("/", wishHandler.CreateWish)
	wishes.Put("/:id", wishHandler.UpdateWish)
	wishes.Delete("/:id", wishHandler.DeleteWish)

	// Goal 路由 - 共同目标（需要JWT认证）
	goals := api.Group("/goals", middleware.JWTAuth())
	goals.Get("/", goalHandler.GetGoals)
	goals.Get("/:id", goalHandler.GetGoal)
	goals.Post("/", goalHandler.CreateGoal)
	goals.Put("/:id", goalHandler.UpdateGoal)
	goals.Delete("/:id", goalHandler.DeleteGoal)

	// QARecord 路由 - 情侣问答（需要JWT认证）
	qaRecords := api.Group("/qa-records", middleware.JWTAuth())
	qaRecords.Get("/", qaRecordHandler.GetQARecords)
	qaRecords.Get("/deleted", qaRecordHandler.GetDeletedQARecords) // 获取已删除的问答
	qaRecords.Get("/:id", qaRecordHandler.GetQARecord)
	qaRecords.Post("/", qaRecordHandler.CreateQARecord)
	qaRecords.Put("/:id", qaRecordHandler.UpdateQARecord)
	qaRecords.Put("/:id/restore", qaRecordHandler.RestoreQARecord)              // 恢复问答
	qaRecords.Delete("/:id", qaRecordHandler.DeleteQARecord)                    // 软删除
	qaRecords.Delete("/:id/permanent", qaRecordHandler.PermanentDeleteQARecord) // 永久删除

	// MediaRecord 路由 - 书影音记录（需要JWT认证）
	mediaRecords := api.Group("/media-records", middleware.JWTAuth())
	mediaRecords.Get("/", mediaRecordHandler.GetMediaRecords)
	mediaRecords.Get("/deleted", mediaRecordHandler.GetDeletedMediaRecords) // 获取已删除的书影音记录
	mediaRecords.Get("/:id", mediaRecordHandler.GetMediaRecord)
	mediaRecords.Post("/", mediaRecordHandler.CreateMediaRecord)
	mediaRecords.Put("/:id", mediaRecordHandler.UpdateMediaRecord)
	mediaRecords.Put("/:id/restore", mediaRecordHandler.RestoreMediaRecord)              // 恢复书影音记录
	mediaRecords.Delete("/:id", mediaRecordHandler.DeleteMediaRecord)                    // 软删除
	mediaRecords.Delete("/:id/permanent", mediaRecordHandler.PermanentDeleteMediaRecord) // 永久删除

	// Gift 路由 - 礼物心愿单（需要JWT认证）
	gifts := api.Group("/gifts", middleware.JWTAuth())
	gifts.Get("/", giftHandler.GetGifts)
	gifts.Get("/:id", giftHandler.GetGift)
	gifts.Post("/", giftHandler.CreateGift)
	gifts.Put("/:id", giftHandler.UpdateGift)
	gifts.Delete("/:id", giftHandler.DeleteGift)

	// RelationshipStat 路由 - 恋爱统计（需要JWT认证）
	relationshipStats := api.Group("/relationship-stats", middleware.JWTAuth())
	relationshipStats.Get("/", relationshipStatHandler.GetRelationshipStats)
	relationshipStats.Get("/:id", relationshipStatHandler.GetRelationshipStat)
	relationshipStats.Post("/", relationshipStatHandler.CreateRelationshipStat)
	relationshipStats.Put("/:id", relationshipStatHandler.UpdateRelationshipStat)
	relationshipStats.Delete("/:id", relationshipStatHandler.DeleteRelationshipStat)

	// 启动服务器
	log.Println("服务器启动在 http://localhost:3000")
	log.Fatal(app.Listen(":3000"))
}
